//
//  MCSelectActionVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/31.
//

import UIKit
import SnapKit
import MJRefresh
import ObjectMapper
import JKSwiftExtension

typealias actionModelBlock = (_ model:MCCreatePlanaddDataModel?,_ index:Int?) -> Void


class MCSelectActionVc: MCBaseVc {
    
    // 0 时间 1 次数
    var actionType:Int = 0
    
    var selectType:Int = 0
    
    var sortValue:Int = 0
    
    @IBOutlet weak var rightSelectActionCollectionView: UICollectionView!
    
    @IBOutlet weak var leftSelectActionTableview: UITableView!
   
    private let leftTableCellIdentifier = "leftTableCellIdentifier"
    
    private let rightTableCellIdentifier = "rightTableCellIdentifier"
    
    private var _selectIndex:Int = 0
    
    private var leftDataSource:Array = [String]()
    
    private var actionModelList:Array = [MCActionInfoRecord?]()
    
    private var count:Int = 1
    
    private let rightCollectionReusableIdentifier = "rightCollectionReusableIdentifier"
    
    var actionModelBlockInfo:actionModelBlock?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "F7F7F9")
        self.navigationItem.title = "添加动作"
        let rightSelectActionLayout = UICollectionViewFlowLayout.init()
        self.rightSelectActionCollectionView.setCollectionViewLayout(rightSelectActionLayout, animated: true)
        
        
        leftSelectActionTableview.register(MCLeftTableCell.self, forCellReuseIdentifier: leftTableCellIdentifier)
        rightSelectActionCollectionView.register(MCRightCollectionCell.self, forCellWithReuseIdentifier: rightTableCellIdentifier)
        
        getLeftData()
        
        self.rightSelectActionCollectionView.register(UINib(nibName: "MCSelectHeaderReusableView", bundle: Bundle.main), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: rightCollectionReusableIdentifier)
        
    }
    
    
    //左边部分
    func getLeftData() -> Void {
        NetWorkRequest(MCActionViewModel.getExercisePosition) { ResponseModel in
            if ResponseModel.code == 200 {
                let bodyList  = Mapper<MCActionbodyModel>().mapArray(JSONString: ResponseModel.dataString)!
                self.leftDataSource = (bodyList.map({ actionbodyModel in
                    return actionbodyModel.dictValue ?? ""
                }))
                
                self.leftDataSource.insert("全部", at: 0)
                self.leftSelectActionTableview.reloadData()
                self.leftSelectActionTableview.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
                self.leftSelectActionTableview.delegate?.tableView?(self.leftSelectActionTableview, didSelectRowAt: IndexPath(item: 0, section: 0))
                
            }else{
                self.view.makeToast("网络失败",position: .center)
            }
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    //动作部分
    func getRightActionData(current:Int,position:String) -> Void {
        NetWorkRequest(MCActionViewModel.getActionPageListApp(current: current, postition: position)) { ResponseModel in
            let actionModel = MCActionInfoModelList(JSONString: ResponseModel.dataString)
            if current == 1 {
                self.actionModelList.removeAll()
                self.actionModelList.append(contentsOf: actionModel?.records ?? [])
            }else {
                self.count += 1
                self.actionModelList.append(contentsOf: actionModel?.records ?? [])
            }
            self.rightSelectActionCollectionView.reloadData()
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
}

extension MCSelectActionVc:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.leftDataSource.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 58
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MCLeftTableCell = tableView.dequeueReusableCell(withIdentifier: leftTableCellIdentifier, for: indexPath) as! MCLeftTableCell
        
        let actionBodyModel = self.leftDataSource[indexPath.row];
        cell.titleInfLabel.text = actionBodyModel
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        _selectIndex = indexPath.row
        
        if indexPath.row == 0 {
            self.count = 1
            getRightActionData(current: self.count, position:"")
        }else {
            self.count = 1
            getRightActionData(current: self.count, position: "\(indexPath.row)")
        }
        self.rightSelectActionCollectionView.scrollToItem(at: NSIndexPath(item: _selectIndex, section: 0) as IndexPath, at: .top, animated: true)
    }
    
    
}

extension MCSelectActionVc:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.actionModelList.count
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let fileListModel = self.actionModelList[section]
        
        return fileListModel?.actionList?.count ?? 0
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10, left: 16, bottom: 0, right: 16)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (UIScreen.main.bounds.size.width * 0.7 - 45) / 2 , height: 110)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:MCRightCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: rightTableCellIdentifier, for: indexPath) as! MCRightCollectionCell
        
        let intrumentListModelInfo = self.actionModelList[indexPath.section]
        
        let listModelInfo = intrumentListModelInfo?.actionList?[indexPath.row]
        
        
        cell.titleInfoLabel.text = listModelInfo?.zhName

        cell.icnImageView.kf.setImage(with:URL(string: listModelInfo?.previewUrl ?? ""))
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: 200, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        var collectionReusableView:UICollectionReusableView!
        if kind == UICollectionView.elementKindSectionHeader {
            let reusableView:MCSelectHeaderReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: rightCollectionReusableIdentifier, for: indexPath) as! MCSelectHeaderReusableView
            let intrumentListModelInfo = self.actionModelList[indexPath.section]
            
            reusableView.titleInfoLabel.text = intrumentListModelInfo?.firstLetterUpper
            
            collectionReusableView = reusableView
        }
        
        return collectionReusableView
        
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        let intrumentListModelInfo = self.actionModelList[indexPath.section]
        
        let listModelInfo = intrumentListModelInfo?.actionList?[indexPath.row]

       
                
        
        if self.actionType == 0 {
            let groupCapacityVc = MCAfterGroupCapacityVc.init()
            groupCapacityVc.actionInfoList = listModelInfo
            weak var weakSelf = self
            groupCapacityVc.actionType = self.actionType
            groupCapacityVc.select = self.selectType
            groupCapacityVc.sortValue = self.sortValue
            groupCapacityVc.timeInfoCapBlock = { (info,index) in
                
                weakSelf?.actionModelBlockInfo?(info,index)
                
                DispatchQueue.main.asyncAfter(deadline:.now() + 1.5) {
                    weakSelf?.navigationController?.jk.popToViewController(as: MCCreateNewPlanVc.self, animated: true)
                }
            }
            
            self.navigationController?.pushViewController(groupCapacityVc, animated: true)
        }
        
        if self.actionType == 1 {
            let afterWeightVc = MCAfterGroupCapacityWeightVc.init()
            afterWeightVc.actionInfoList = listModelInfo
            weak var weakSelf = self
            afterWeightVc.actionType = self.actionType
            afterWeightVc.select = self.selectType
            afterWeightVc.sortValue = self.sortValue
            afterWeightVc.actionNumberOrWidgetBlocks = { (info ,index)  in
                weakSelf?.actionModelBlockInfo?(info,index)
                DispatchQueue.main.asyncAfter(deadline:.now() + 1.5) {
                    weakSelf?.navigationController?.jk.popToViewController(as: MCCreateNewPlanVc.self, animated: true)
                }
            }
            
            self.navigationController?.pushViewController(afterWeightVc, animated: true)
        }
    }
}
